package wassalt.client;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.Filterable;
import android.widget.TextView;

public class ContactsAdapter extends CursorAdapter implements Filterable {

	private ContentResolver mCR;
	private int layout;

	public ContactsAdapter(Context context, Cursor c) {
		super(context, c);
		// TODO Auto-generated constructor stub
		mCR = context.getContentResolver();
	}

	@Override
	public void bindView(View arg0, Context arg1, Cursor arg2) {
//		TextView text = (TextView)arg0.findViewById(R.id.name);
		// TODO Auto-generated method stub
		String tex = arg2.getString(1)+"\n"+ arg2.getString(2);
		((TextView) arg0).setText(tex);
	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		// TODO Auto-generated method stub
		final LayoutInflater inflater = LayoutInflater.from(context);
		final TextView view = (TextView) inflater.inflate(
				R.layout.text_view, parent, false);

		view.setText(cursor.getString(1) + "\n" + cursor.getString(2));


		
		return view;
	}

	@Override
	public String convertToString(Cursor cursor) {

		return (cursor.getString(1) + " <" + cursor.getString(2) + ">");
	}

	public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
		if (getFilterQueryProvider() != null) {
			return getFilterQueryProvider().runQuery(constraint);
		}

		StringBuilder buffer = null;
		String[] args = null;
		String selection = "";
		if (constraint != null) {
			buffer = new StringBuilder();
			buffer.append("UPPER(");
			buffer.append(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
			buffer.append(ContactsContract.CommonDataKinds.Phone.NUMBER);
			buffer.append(") GLOB ?");
			selection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
					+ " LIKE '" + "%" + constraint.toString() + "%'" + " or "
					+ ContactsContract.CommonDataKinds.Phone.NUMBER + " LIKE '"
					+ "%" + constraint.toString() + "%'";
			// args = new String[] { constraint.toString().toUpperCase() + "*"
			// };
		}

		return mCR.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
				CreateOffer.PEOPLE_PROJECTION, selection, null,
				Contacts.DISPLAY_NAME);
	}
	
}